from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QPushButton,
                               QTableWidget, QTableWidgetItem, QDialog, QLabel,
                               QLineEdit, QMessageBox, QSpinBox)
from PySide6.QtCore import Qt
from utils.db import db


class ServiceDialog(QDialog):
    def __init__(self, parent=None, service_data=None):
        super().__init__(parent)
        self.service_data = service_data
        self.setup_ui()
        if service_data:
            self.load_service_data()

    def setup_ui(self):
        self.setWindowTitle("服务项目信息")
        self.setMinimumWidth(400)

        layout = QVBoxLayout(self)
        layout.setSpacing(15)

        # 服务名称
        self.name_input = QLineEdit()
        self.name_input.setPlaceholderText("请输入服务名称")
        layout.addWidget(QLabel("服务名称:"))
        layout.addWidget(self.name_input)

        # 服务价格
        self.price_input = QLineEdit()
        self.price_input.setPlaceholderText("请输入价格")
        layout.addWidget(QLabel("价格(元):"))
        layout.addWidget(self.price_input)

        # 服务时长
        self.duration_input = QSpinBox()
        self.duration_input.setRange(0, 360)  # 0-360分钟
        self.duration_input.setSuffix(" 分钟")
        layout.addWidget(QLabel("服务时长:"))
        layout.addWidget(self.duration_input)

        # 服务描述
        self.description_input = QLineEdit()
        self.description_input.setPlaceholderText("请输入服务描述")
        layout.addWidget(QLabel("服务描述:"))
        layout.addWidget(self.description_input)

        # 按钮
        button_layout = QHBoxLayout()
        self.save_btn = QPushButton("保存")
        self.cancel_btn = QPushButton("取消")

        self.save_btn.clicked.connect(self.save_service)
        self.cancel_btn.clicked.connect(self.reject)

        button_layout.addWidget(self.save_btn)
        button_layout.addWidget(self.cancel_btn)

        layout.addLayout(button_layout)

    def load_service_data(self):
        """加载服务数据"""
        self.name_input.setText(self.service_data["name"])
        self.price_input.setText(str(self.service_data["price"]))
        self.duration_input.setValue(self.service_data["duration"] or 0)
        self.description_input.setText(self.service_data["description"] or "")

    def save_service(self):
        """保存服务信息"""
        try:
            name = self.name_input.text().strip()
            price = self.price_input.text().strip()
            duration = self.duration_input.value()
            description = self.description_input.text().strip()

            if not name:
                raise ValueError("服务名称不能为空！")
            if not price:
                raise ValueError("价格不能为空！")
            try:
                price = float(price)
                if price < 0:
                    raise ValueError()
            except:
                raise ValueError("价格必须是有效的数字！")

            if self.service_data:  # 更新
                sql = """
                UPDATE services 
                SET name=?, price=?, duration=?, description=?
                WHERE id=?
                """
                db.execute(sql, (name, price, duration, description, self.service_data["id"]))
            else:  # 新建
                sql = """
                INSERT INTO services (name, price, duration, description)
                VALUES (?, ?, ?, ?)
                """
                db.execute(sql, (name, price, duration, description))

            self.accept()

        except Exception as e:
            QMessageBox.critical(self, "错误", str(e))


class ServicePage(QWidget):
    def __init__(self):
        super().__init__()
        self.setup_ui()
        self.load_services()

    def setup_ui(self):
        layout = QVBoxLayout(self)
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(20)

        # 工具栏
        toolbar = QHBoxLayout()
        self.add_btn = QPushButton("添加服务")
        self.refresh_btn = QPushButton("刷新")

        self.add_btn.setObjectName("primaryButton")
        self.refresh_btn.setObjectName("secondaryButton")

        self.add_btn.clicked.connect(self.add_service)
        self.refresh_btn.clicked.connect(self.load_services)

        toolbar.addWidget(self.add_btn)
        toolbar.addWidget(self.refresh_btn)
        toolbar.addStretch()

        # 服务表格
        self.table = QTableWidget()
        self.table.setColumnCount(6)
        self.table.setHorizontalHeaderLabels([
            "ID", "服务名称", "价格", "时长(分钟)", "描述", "操作"
        ])

        # 设置表格样式
        self.table.setSelectionBehavior(QTableWidget.SelectRows)
        self.table.setEditTriggers(QTableWidget.NoEditTriggers)
        self.table.horizontalHeader().setStretchLastSection(True)

        layout.addLayout(toolbar)
        layout.addWidget(self.table)

        self.apply_styles()

    def apply_styles(self):
        self.setStyleSheet("""
            QWidget {
                background-color: white;
            }
            #primaryButton {
                background-color: #5352ed;
                color: white;
                border: none;
                padding: 8px 15px;
                border-radius: 4px;
            }
            #primaryButton:hover {
                background-color: #3742fa;
            }
            #secondaryButton {
                background-color: #dcdde1;
                border: none;
                padding: 8px 15px;
                border-radius: 4px;
            }
            #secondaryButton:hover {
                background-color: #c8c9cc;
            }
            QTableWidget {
                border: none;
                gridline-color: #f1f2f6;
            }
            QTableWidget::item {
                padding: 8px;
            }
            QTableWidget::item:selected {
                background-color: #5352ed22;
            }
            QHeaderView::section {
                background-color: #f8f9fa;
                padding: 8px;
                border: none;
                border-bottom: 2px solid #dcdde1;
            }
        """)

    def load_services(self):
        """加载服务列表"""
        self.table.setRowCount(0)
        sql = "SELECT * FROM services ORDER BY id"
        services = db.fetch_all(sql)

        for row, service in enumerate(services):
            self.table.insertRow(row)

            self.table.setItem(row, 0, QTableWidgetItem(str(service["id"])))
            self.table.setItem(row, 1, QTableWidgetItem(service["name"]))
            self.table.setItem(row, 2, QTableWidgetItem(f"¥{service['price']:.2f}"))
            self.table.setItem(row, 3, QTableWidgetItem(str(service["duration"] or "-")))
            self.table.setItem(row, 4, QTableWidgetItem(service["description"] or ""))

            # 操作按钮
            btn_widget = QWidget()
            btn_layout = QHBoxLayout(btn_widget)
            btn_layout.setContentsMargins(0, 0, 0, 0)

            edit_btn = QPushButton("编辑")
            delete_btn = QPushButton("删除")

            edit_btn.clicked.connect(lambda checked, s=dict(service): self.edit_service(s))
            delete_btn.clicked.connect(lambda checked, id=service["id"]: self.delete_service(id))

            btn_layout.addWidget(edit_btn)
            btn_layout.addWidget(delete_btn)

            self.table.setCellWidget(row, 5, btn_widget)

    def add_service(self):
        """添加服务"""
        dialog = ServiceDialog(self)
        if dialog.exec_() == QDialog.Accepted:
            self.load_services()

    def edit_service(self, service_data):
        """编辑服务"""
        dialog = ServiceDialog(self, service_data)
        if dialog.exec_() == QDialog.Accepted:
            self.load_services()

    def delete_service(self, service_id):
        """删除服务"""
        reply = QMessageBox.question(
            self, "确认删除",
            "确定要删除这个服务项目吗？此操作不可恢复！",
            QMessageBox.Yes | QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            try:
                # 检查是否有关联的交易记录
                sql = "SELECT COUNT(*) as count FROM transactions WHERE service_id = ?"
                result = db.fetch_one(sql, (service_id,))
                if result and result["count"] > 0:
                    raise ValueError("该服务项目已有交易记录，无法删除！")

                sql = "DELETE FROM services WHERE id = ?"
                db.execute(sql, (service_id,))
                self.load_services()
            except Exception as e:
                QMessageBox.critical(self, "错误", f"删除失败：{str(e)}")
